﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class DatabaseCheckDataAndLogonSameDrive:IssueTypeCheckBase
    {
        public DatabaseCheckDataAndLogonSameDrive()
        {
            IssueTypeId = 3007;
        }

        public override void Check()
        {
            HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
            Issue issue;

             /*
              * This rule checks that data and log files are not placed on the same logical drive. 
              * This is a general recommendation that helps separate IO for data pages from log operations.
              */

            var qrylog = from df in dc.DatabaseFiles

                         where df.FileGroup.Contains("LOG")

                         select df;

            var qryprim = from df in dc.DatabaseFiles

                          where df.FileGroup.Contains("PRIMARY")

                          select df;

            var qryjoin = from l in qrylog
                          join p in qryprim on l.DatabaseID equals p.DatabaseID
                          
                          where ! l.Drive.Contains("C")&& ! p.Drive.Contains("C")

                          &&

                          l.Drive==p.Drive && p.SizeInMb > 1024 

                          select new
                          {
                              DatabaseId = l.DatabaseID,
                              DatabaseName = l.Database.DatabaseName,
                              logFile = l.File,
                              primFile = p.File
                          };
            // Iterate through the Linq Query 
            foreach (var item in qryjoin)
            {
                int databaseId = item.DatabaseId;
                //Get Issuetype object

                issue = new Issue();

                //Get Issuetype object  And Create a new  Global issue object 
                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                issue.IssueType = issueType;
                issue.TargetId = item.DatabaseId;
                issue.Description = issueType.Description.Replace("{Database}", item.DatabaseName).Replace("{Logfile}", item.logFile.ToString()).Replace("{Drive}", item.primFile.ToString());

                dc.Issues.InsertOnSubmit(issue);
            }

            dc.SubmitChanges();


        }
       
       }
}
